<template>
  <div class="demo-content">
    <h1>画布拖拽和元素拖拽</h1>
    <section class="demo-text">
      <canvas id="canvas" width="1200" height="600" ref="canvas"></canvas>
      <h2>说明</h2>
      <p>Fabric已经对事件进行了封装，当前事件有target时拖拽当前元素，当前事件无target时，拖拽整个画布
        <br>选中有元素时只拖拽元素，未选择元素时拖拽整个图层
      </p>
      <button @click="handleclick">测速</button>
      <form>
                <select name="" id="" v-model="test" @input="change">
          <option value="all">all</option>
          <option value="123">123</option>
        </select>
      </form>

      <p style="text-align:right;padding-right:60px">@王睿杰 2019.1.21</p>
    </section>
  </div>
</template>
<script>
import { fabric } from  "@/js/fabric";
export default {
  data(){
    return {
      test:"all"
    }
  },
  methods:{
    handleclick(){
      if(this.test=='all'){
        this.test='123'
      }else{
        this.test='all'
      }
    },
    change(){
      console.log(change)
    }
  },
  mounted() {
    let panning = false;
    this.$nextTick(() => {
      var canvas = new fabric.Canvas("canvas");
      var rect1 = new fabric.Rect({
        top: 50,
        left: 50,
        width: 70,
        height: 70,
        fill: "red"
      });
      canvas.add(rect1);
      var rect2 = new fabric.Rect({
        top: 50,
        left: 150,
        width: 70,
        height: 70,
        fill: "red"
      });
      canvas.add(rect2);
      var rect3 = new fabric.Rect({
        top: 50,
        left: 250,
        width: 70,
        height: 70,
        fill: "red"
      });
      canvas.add(rect3);
      //鼠标按下
      canvas.on("mouse:down", function(e) {
        //按住alt键才可拖动画布
        if (!e.target) {
          panning = true;
          canvas.selection = false;
        }
      });
      //鼠标抬起
      canvas.on("mouse:up", function(e) {
        panning = false;
        canvas.selection = true;
      });

      //鼠标移动
      canvas.on("mouse:move", function(e) {
        
        if (panning && e && e.e) {
          var delta = new fabric.Point(e.e.movementX, e.e.movementY);
          canvas.relativePan(delta);
        }
        if(!e||!e.target)return;
        e.target.setCoords();
        canvas.forEachObject(function(obj) {
          if (obj === e.target) return;
          obj.set("opacity", e.target.intersectsWithObject(obj) ? 0.5 : 1);
        });
      });
    });
  }
};
</script>
